import { history } from '@umijs/max';
import { message } from 'antd';
import queryString from 'querystring';
import {SessionStorage} from '@/utils/storage'
import {TOKEN} from '@/common/Constants';
const { REACT_APP_ENV, URL_CONFIG } = process.env;
// 运行时配置
export const request = {
  // 统一的请求设定
  timeout: 30000,
  baseURL: REACT_APP_ENV ? JSON.parse(URL_CONFIG).api : '',
  paramsSerializer(params) {
    return queryString.stringify(params);
  },
  // 请求拦截器
  requestInterceptors: [
    (config) => {
      // 拦截请求配置，进行个性化处理。
      config.headers = {
        'Content-Type':
          config.headers && config.headers['Content-Type']
            ? config.headers['Content-Type']
            : 'application/json',
        'token': SessionStorage.get(TOKEN),
      };
      // 如果post请求,data为空的话,content-type无效,接口会报媒体类型不支持
      if (config.method === 'post' && !config.data) {
        config.data = {};
      }
      return { ...config };
    },
  ],
  // 响应拦截器
  responseInterceptors: [
    [
      (response) => {
        // 拦截响应数据，进行个性化处理
        if (response.data.code === 0) {
          // 1.成功
          //loading
          if (response.data.hasOwnProperty('data')) {
            return response.data;
          } else {
            return response
          }
        } else {
          if (Number(response.data.code) === 1401) {
            // 2.session过期
            message.destroy();
            message.error(response.data.msg);
            SessionStorage.clear();
            setTimeout(function () {
              history.replace('/session/login');
            }, 1000);
          } else if (
            response.headers['content-type'] &&
            response.headers['content-type'].includes(
              'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
            )
          ) {
            // response.headers['content-type'].includes('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') 此处用于接收文件流，需要后端返回Content-Type标明为文件类型，office文件content-type文件类型大全https://blog.csdn.net/xiaoranzhizhu/article/details/70473734
            return response;
          } else if (response.config.responseType === 'blob') {
            if (response.data.type === 'application/json') {
              let reader = new FileReader();
              reader.readAsText(response.data, 'utf-8');
              reader.onload = (e) => {
                message.destroy();
                message.info(JSON.parse(reader.result).msg);
              };
            } else {
              return response;
            }
          } else if (response.config.responseType === 'arraybuffer') {
            return response;
          } else if (response.data.msg) {
            message.destroy();
            message.error(response.data.msg);
          } else {
            message.error('网络开小差了哦，请稍后再试。');
          }
          return Promise.reject(response.data);
        }
      },
      (error) => {
        message.destroy();
        console.log(error);
        if (!navigator.onLine) {
          message.warning('网络开小差了哦，请稍后再试。');
        }
        if (error.response && error.response.data && error.response.data.msg) {
          if (error.response.status === 500) {
            message.error('服务器开小差了哦，请稍后再试。');
          } else {
            message.error(error.response.data.msg);
          }
        } else {
          message.error('网络开小差了哦，请稍后再试。');
        }
        return Promise.reject(error);
      },
    ],
  ],
};
